package main

import (
	json2 "encoding/json"
	"fmt"
	"goWebStudy/web_db1/model"
	"net/http"
)

// 创键处理器函数
func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "你发送的请求的请求地址是：", r.URL.Path)
	fmt.Fprintln(w, "你发送的请求的请求地后的查询字符串是：", r.URL.RawQuery)
	fmt.Fprintln(w, "请求头中的所有信息:", r.Header)
	//获取请求体中内容的长度
	//length := r.ContentLength
	////创建一个字节切片
	//body := make([]byte, length)
	////读取请求体
	//r.Body.Read(body)
	//fmt.Fprintln(w, "请求体中的内容是：", string(body))
	r.ParseForm()
	fmt.Fprintln(w, "Form中的数据：", r.Form)
	fmt.Fprintln(w, "Form中POST的数据：", r.PostForm)
	fmt.Fprintln(w, "-------------------")
	fmt.Fprintln(w, "URL中user请求的参数的值是：", r.FormValue("user"))
	fmt.Fprintln(w, "Form中username请求的参数的值是：", r.PostFormValue("username"))
}
func testJsonRes(w http.ResponseWriter, r *http.Request) {
	//设置响应内容的类型
	w.Header().Set("Content-Type", "application/json")
	student := model.Student{
		Id:    1,
		Name:  "admin",
		Age:   18,
		Class: "jikeyiban",
	}
	//将student转换为Json格式
	json, _ := json2.Marshal(student)
	//将json格式的数据响应给客户端
	w.Write(json)
}
func testRedire(w http.ResponseWriter, r *http.Request) {
	//设置响应头中的Location属性
	w.Header().Set("Location", "https://www.baidu.com")
	//设置响应的状态码
	w.WriteHeader(302)
}

func main() {
	http.HandleFunc("/hello", handler)
	http.HandleFunc("/testJson", testJsonRes)
	http.HandleFunc("/testRedirect", testRedire)

	http.ListenAndServe(":8080", nil)
}
